﻿using System;
using System.Configuration;
using System.Web.Mvc;
using WebStickyNotes.Data.Access;
using WebStickyNotes.Helpers;
using WebStickyNotes.Models;
using WebStickyNotes.Resources;

namespace WebStickyNotes.Controllers
{
    public class SignInController : Controller
    {
        private readonly string _connectionType;
        private readonly string _connectionString;

        public SignInController()
        {
            _connectionType = ConfigurationManager.AppSettings["ConnectionType"];
            _connectionString = ConfigurationManager.ConnectionStrings["WebStickyNotesData"].ConnectionString;
        }

        [HttpGet]
        public ActionResult Index()
        {
            var model = new SignInModel
                            {
                                Message = new Message()
                            };

            return View(model);
        }

        [HttpPost]
        public ActionResult Index(SignInModel model)
        {
			using (var supplier = new Supplier(_connectionType, _connectionString))
            {
                var authenticated = false;

                ValidateSignInModel(model);

                if (ModelState.IsValid)
                {
                    var taskPerson = supplier.DataAccess.GetTaskPersonByEmail(model.EmailAddress);

                    if (taskPerson.Id > 0)
                    {
                        authenticated = EncryptionHelper.ComparePassword(taskPerson, model.Password);
                        if (authenticated)
                        {
                            SecurityHelper.SetSignIn(taskPerson.Id, taskPerson.TaskRoleId);

                            // Audit
                            AuditHelper.AuditAction(supplier.DataAccess, "Signed In", taskPerson.Id);

                            // Each time someone logs in, archive off old audit records
                            supplier.DataAccess.DeleteTaskAudits(DateTime.Today.AddMonths(-6));
                        } else
                        {
                            // Audit
                            AuditHelper.AuditAction(supplier.DataAccess, "Failed Sign In", taskPerson.Id);
                        }
                    }
                }

                if (authenticated)
                {
                    if (model.MobileSite)
                    {
                        return RedirectToAction("Index", "Mobile");
                    }
                    return RedirectToAction("Index", "Home");
                }

                model.Message = new Message
                                    {
                                        Class = "error",
                                        Text = Labels.LoginFailed
                                    };

                return View(model);
            }
        }

        [HttpGet]
        public ActionResult SignOut()
        {
			using (var supplier = new Supplier(_connectionType, _connectionString))
            {
                // Audit
                AuditHelper.AuditAction(supplier.DataAccess, "Signed Out", SecurityHelper.GetSignedInUserId());

                SecurityHelper.SignOut();

                return RedirectToAction("Index");
            }
        }

        private void ValidateSignInModel(SignInModel model)
        {
            if (string.IsNullOrEmpty(model.EmailAddress))
            {
                ModelState.AddModelError("EmailAddress", Labels.PleaseEnterEmail);
            }

            if (string.IsNullOrEmpty(model.Password))
            {
                ModelState.AddModelError("Password", Labels.PleaseEnterPassword);
            }
        }
    }
}